<template>
  <div class="product">
    <!-- 条件搜索 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input
          placeholder="请输入需要查询的内容"
          v-model="searchall"
          clearable
          @clear="clearsearch()"
        >
          <template slot="prepend">按全部查询：</template>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="allSearch()"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="10">
        <el-input
          placeholder="请输入需要查询的书名"
          v-model="search"
          clearable
          @clear="clearsearch()"
        >
          <template slot="prepend">按书名查询：</template>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch()"
          ></el-button>
        </el-input>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input
          placeholder="请输入需要查询的作者"
          v-model="search1"
          clearable
          @clear="clearsearch()"
        >
          <template slot="prepend">按作者查询：</template>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="authorSearch()"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="10">
        <el-input
          placeholder="请输入需要查询的出版社"
          v-model="search2"
          clearable
          @clear="clearsearch()"
        >
          <template slot="prepend">按出版社查：</template>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="pressSearch()"
          ></el-button>
        </el-input>
      </el-col>
    </el-row>
    <!-- 上传图书 -->
    <el-row>
      <el-col>
        <el-button
          class="insbut"
          type="primary"
          size="mini"
          icon="el-icon-circle-plus-outline"
          @click="dialogFormVisible = true"
          >出售二手书</el-button
        >
      </el-col>
    </el-row>
    <!-- table显示数据 -->
    <div class="conter">
      <el-table :data="tableData2" border stripe>
        <el-table-column
          type="index"
          :index="indexNum"
          label="序号"
          width="40"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="booknumber"
          label="图书编号"
          width="60"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="bookname"
          label="图书名称"
          width=""
          align="center"
        >
          <template slot-scope="scpoe">
            <span>{{ scpoe.row.bookname }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="booktype_id"
          label="图书类型"
          width=""
          align="center"
        >
        </el-table-column>
        <el-table-column prop="author" label="图书作者" width="" align="center">
        </el-table-column>
        <el-table-column prop="press" label="出版社" width="" align="center">
        </el-table-column>
        <el-table-column prop="image" label="封面图" width="" align="center">
          <template slot-scope="scope">
            <img :src="api + scope.row.image" min-width="80" height="80" />
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="简介"
          width=""
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ scope.row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="原价" width="60" align="center">
        </el-table-column>
        <el-table-column prop="vipprice" label="现价" width="60" align="center">
        </el-table-column>
        <el-table-column prop="freight" label="运费" width="50" align="center">
        </el-table-column>
        <el-table-column prop="number" label="库存" width="50" align="center">
        </el-table-column>
        <el-table-column
          prop="oldnewdegree"
          label="新旧程度"
          width="50"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="下架/上架"
          prop="sheif"
          width="140"
          align="center"
        >
          >
          <template slot-scope="scpoe">
            <el-switch
              v-model="scpoe.row.sheif"
              active-text="上架"
              inactive-text="下架"
              @change="toggle(scpoe.row.id)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="Editbooks(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="Deletebooks(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @next-click="handleNextClick"
        @prev-click="handlePrevClick"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="5"
        :current-page="currentpage"
        background
        layout="total,sizes, prev, pager, next, jumper"
        :total="tableData_length"
      >
      </el-pagination>
    </div>
    <!-- 添加产品弹框 对话框-->
    <el-dialog
      :title="isEdit ? '编辑' : '出售二手书'"
      :visible.sync="dialogFormVisible"
      center
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="图书编号"
          :label-width="formLabelWidth"
          prop="booknumber"
        >
          <el-input v-model="form.booknumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="图书名称"
          :label-width="formLabelWidth"
          prop="bookname"
        >
          <el-input v-model="form.bookname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="图书分类"
          :label-width="formLabelWidth"
          prop="value"
        >
          <el-select
            v-model="value"
            value-key="id"
            @change="searchSelect(value)"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="图书作者"
          :label-width="formLabelWidth"
          prop="author"
        >
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" :label-width="formLabelWidth" prop="press">
          <el-input v-model="form.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadimageapi + '/useruploadimage'"
            :show-file-list="false"
            name="imagefiles"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" :label-width="formLabelWidth" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="原价" :label-width="formLabelWidth" prop="price">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="现价"
          :label-width="formLabelWidth"
          prop="vipprice"
        >
          <el-input v-model="form.vipprice" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="运费" :label-width="formLabelWidth" prop="freight">
          <el-input v-model="form.freight" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="数量" :label-width="formLabelWidth" prop="number">
          <el-input v-model="form.number" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="新旧程度"
          :label-width="formLabelWidth"
          prop="oldnewdegree"
        >
          <el-input v-model="form.oldnewdegree" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="isEdit" type="primary" @click="updatebooks"
          >提 交</el-button
        >
        <el-button v-else type="primary" @click="insertbooks('form')"
          >上 传</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  data() {
    return {
      tableData: [],
      options: [],
      value: "",
      form: {
        booknumber: "",
        bookname: "",
        author: "",
        press: "",
        image: "",
        price: "",
        vipprice: "",
        content: "",
        number: "",
        freight: "",
        oldnewdegree: "",
        booktype_id: "",
        user_id: sessionStorage.getItem("id")
      },
      rules: {
        booknumber: [
          { required: true, message: "请输入图书编号", trigger: "blur" },
          { min: 2, message: "长度至少两个字符", trigger: "blur" }
        ],
        bookname: [
          { required: true, message: "请输入书名", trigger: "blur" },
          { min: 1, message: "长度至少一个字符", trigger: "blur" }
        ],
        author: [
          { required: true, message: "请输入图书作者", trigger: "blur" },
          { min: 1, message: "长度至少一个字符", trigger: "blur" }
        ],
        press: [
          { required: true, message: "请输入图书作者", trigger: "blur" },
          { min: 1, message: "长度至少一个字符", trigger: "blur" }
        ],
        price: [
          {
            required: true,
            message: "请输入图书价格",
            trigger: "blur"
          }
        ],
        vipprice: [
          {
            required: true,
            message: "请输入图书现价",
            trigger: "blur"
          }
        ],
        content: [
          { required: true, message: "请输入图书简介", trigger: "blur" },
          { min: 10, message: "长度至少十个字符", trigger: "blur" }
        ],
        number: [
          {
            required: true,
            message: "请输入图书数量",
            trigger: "blur"
          }
        ],
        oldnewdegree: [
          { required: true, message: "请输入图书新旧程度", trigger: "blur" }
        ]
      },
      formLabelWidth: "80px",
      imageUrl: "",
      dialogFormVisible: false,
      //图片地址拼接 显示图片
      api: this.imageapi,
      uploadimageapi: this.uploadimageapi, //全局定义
      isEdit: false,
      search: "", //书名查询
      search1: "", //作者查询
      search2: "", //编号查询
      searchall: "", //全部查询
      currentpage: 1, //当前页面
      tableData2: [], //每页显示条目
      tableData_length: 0, //总条目数
      pageSize: 5,
      oldPage: -1 //记录状态
    };
  },
  created() {},
  mounted() {
    this.init();
    this.initbooktype();
  },
  methods: {
    //获取图书分类
    initbooktype() {
      this.$http.get("/showbookscategory").then(res => {
        // console.log(res)
        this.options = res.data;
      });
    },
    //获取选择器图书分类的对应id
    searchSelect(value) {
      this.form.booktype_id = value;
    },
    // 先上传图片
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.image = res.path;
    },
    // 提交图片和数据去服务器 插入数据
    insertbooks(form) {
      const that = this;
      that.$refs[form].validate(valid => {
        if (valid) {
          that.$http
            .post("/usersuccessuploadimage", that.form)
            .then(res => {
              if (res.status == 200) {
                that.$message({
                  message: "上传成功...",
                  type: "success"
                });
                that.init();
                this.reload(); //刷新页面 不会出现白屏
              } else {
                that.$message({
                  message: "上传失败...",
                  type: "error"
                });
              }
              // console.log(res);
              that.dialogFormVisible = false;
              this.reload();
            })
            .catch(function() {
              that.$message({
                message: "上传失败...",
                type: "error"
              });
            });
        } else {
          that.$message({
            message: "请完善信息...",
            type: "error"
          });
        }
      });
    },
    //请求后端数据
    init() {
      const that = this;
      const user_id = that.form.user_id;
      this.$http
        .post("/userselectbooks", { user_id })
        .then(res => {
          // console.log(res);
          that.tableData = res.data;
          that.tableData_length = res.data.length;
          this.handleCurrentChange(1); //默认显示第一页条目
          for (let i in that.tableData) {
            if (that.tableData[i].sheif == 1) {
              that.tableData[i].sheif = true;
            } else {
              that.tableData[i].sheif = false;
            }
          }
        })
        .catch(function() {
          alert("请求数据失败...");
        });
    },
    //修改后请求后端数据
    updateinit() {
      const that = this;
      const user_id = that.form.user_id;
      this.$http
        .post("/userselectbooks", { user_id })
        .then(res => {
          // console.log(res);
          that.tableData = res.data;
          that.tableData_length = res.data.length;
          that.handleCurrentChange(that.oldPage);
          for (let i in that.tableData) {
            if (that.tableData[i].sheif == 1) {
              that.tableData[i].sheif = true;
            } else {
              that.tableData[i].sheif = false;
            }
          }
        })
        .catch(function() {
          alert("请求数据失败...");
        });
    },
    //element table自带序号
    indexNum(index) {
      return (this.currentpage - 1) * this.pageSize + index + 1;
    },
    // switch开关改变 触发的回调函数 下架或上架
    toggle(id) {
      console.log(id);
      this.$http.post("/sheifselectbooksswitch", { id });
    },
    //编辑图书 返回数据到表单
    Editbooks(item) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.imageUrl = this.api + item.image;
      this.form = JSON.parse(JSON.stringify(item));
      this.value = JSON.parse(JSON.stringify(item.booktype_id));
    },
    //更新编辑好的图书
    updatebooks() {
      const that = this;
      that.$http
        .post("/updatebooks", that.form)
        .then(res => {
          if (res.status == 204) {
            that.$message({
              message: "更新数据成功...",
              type: "success"
            });
            that.updateinit();
            // that.$forceUpdate();
            that.dialogFormVisible = false;
            that.isEdit = false;
          } else {
            that.$message({
              message: "更新数据失败...",
              type: "error"
            });
          }
          // console.log(res);
          that.dialogFormVisible = false;
          that.form.booknumber = null;
          that.form.bookname = null;
          that.form.author = null;
          that.form.press = null;
          that.form.image = null;
          that.form.price = null;
          that.form.vipprice = null;
          that.form.content = null;
          that.form.number = null;
          that.form.freight = null;
          that.value = null;
          that.form.oldnewdegree = null;
        })
        .catch(function() {
          that.$message({
            message: "更新数据失败...",
            type: "error"
          });
        });
    },
    //软删除数据 可恢复
    Deletebooks(id) {
      const that = this;
      that
        .$confirm("此操作将数据回收至回收站,可恢复, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          that.$http.post("/softdeletebooks", { id }),
            that.$message({
              type: "success",
              message: "删除成功!"
            });
          for (let i in that.tableData2) {
            if (that.tableData2[i].id == id) {
              that.tableData2.splice(i, 1); //删除不请求数据，直接在数组中删除
              break;
            }
          }
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //处理数据,分页
    handleTableData() {
      this.tableData2 = this.tableData.slice(
        (this.currentpage - 1) * this.pageSize,
        this.currentpage * this.pageSize
      );
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleTableData();
    },
    //点击中间页的按钮 执行的方法
    handleCurrentChange(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向前的按钮 执行的方法
    handlePrevClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向后的按钮 执行的方法
    handleNextClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    // 按照书名搜索
    handleSearch() {
      if (this.search == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else {
        let search = this.search;
        this.tableData = this.tableData.filter(item => {
          let searchField = { bookname: item.bookname };
          return Object.keys(searchField).some(key => {
            return (
              String(item[key])
                .toLowerCase()
                .indexOf(search) > -1
            );
          });
        });
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
    // 按照图书作者搜索
    authorSearch() {
      if (this.search1 == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else {
        let search = this.search1;
        this.tableData = this.tableData.filter(item => {
          let searchField = { author: item.author };
          return Object.keys(searchField).some(key => {
            return (
              String(item[key])
                .toLowerCase()
                .indexOf(search) > -1
            );
          });
        });
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
    // 按照图书作者搜索
    pressSearch() {
      if (this.search2 == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else {
        let search = this.search2;
        this.tableData = this.tableData.filter(item => {
          let searchField = { press: item.press };
          return Object.keys(searchField).some(key => {
            return (
              String(item[key])
                .toLowerCase()
                .indexOf(search) > -1
            );
          });
        });
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
    // 按全部查询
    allSearch() {
      if (this.searchall == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else if (this.searchall) {
        this.tableData = this.tableData.filter(item => {
          let res = JSON.stringify(item);
          if (res.indexOf(this.searchall) != -1) {
            return true;
          } else {
            return false;
          }
        });
      } else {
        this.tableData2 = this.tableData;
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
    // 清除查询框 调用分页函数
    clearsearch() {
      this.init();
    }
  }
};
</script>

<style scoped>
.el-row {
  margin: 10px auto;
}
.el-pagination {
  text-align: center;
  margin: 10px 0px 20px 0px;
}
.avatar-uploader /deep/ .el-upload {
  border: 2px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>